<?php
/**
 * 体检报告
 *
 * User: kaikaic
 * Date: 2018/12/2
 * Time: 15:30
 */

namespace app\exam\model;

use app\exam\service\MecItemService;
use app\exam\service\MecService;
use app\exam\service\MecSetService;
use app\exam\service\ReportService;
use service\ExcelService;

class ItemModel {

    /**
     * 读取EXCEL文件数据
     */
    public function readExcelFile($excelFile) {
        $excelFile = env('root_path') . $excelFile;
        $excelData = ExcelService::importExcel($excelFile);
        if (!$excelData) {
            return 0;
        }

        $importCount = 0;
        for ($i=0; $i<count($excelData); $i++) {
            $tmp = $excelData[$i];
            if (count($tmp) != 6) {
                continue;
            }

            $params = array();
            $params['mec_name'] = trim($tmp[0]);
            $params['exam_item_class'] = trim($tmp[1]);
            $params['name'] = trim($tmp[2]);
            $params['intro'] = trim($tmp[3]);
            $params['price'] = trim($tmp[4]);
            $params['purpose'] = trim($tmp[5]);
            // 数据记录
            $rs = $this->doImport($params);
            if ($rs) {
                $importCount++;
            }
        }

        return $importCount;
    }

    /**
     * 导入实现
     *
     * @param $data
     * @return bool
     */
    private function doImport($data) {
        $data = $this->excelDataFilter($data);
        if (!$data) {
            return false;
        }

        // 医院是否存在
        $mec_name = $data['mec_name'];
        $mec = MecService::getInstance()->single(array('name'=>$mec_name));
        if (!$mec) {
            return false;
        }
        // 项目是否存在
        $exam_item_name = $data['exam_item_class'];
        $exam_item_class = MecItemService::getInstance()->single(array('name'=>$exam_item_name));
        if (!$exam_item_class) {
            return false;
        }
        $params = array();
        $params['mec_id'] = $mec['id'];
        $params['item_set_id'] = $exam_item_class['id'];
        $params['name'] = $data['name'];
        $params['intro'] = $data['intro'];
        $params['price'] = $data['price'];
        $params['purpose'] = $data['purpose'];
        $params['status'] = 1;
        $params['sort'] = MecItemService::getInstance()->getMaxSort() + 1;
        $params['create_time'] = time();

        return MecItemService::getInstance()->insert($params,1);
    }

    /**
     * 对excel数据过滤
     */
    private function excelDataFilter($data) {
        if (!$data['mec_name'] || !$data['exam_item_class'] || !$data['name']) {
            return array();
        }
        return $data;
    }
}

